import 'dart:async';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_douban/config/Http_service.dart';
import 'package:flutter_douban/config/app_config.dart';
import 'package:flutter_douban/config/event_bus_util.dart';
import 'package:flutter_douban/config/sqflite/note_db_provider.dart';
import 'package:flutter_douban/loading/custom_footer.dart';
import 'package:flutter_douban/loading/custom_header.dart';
import 'package:flutter_douban/main_page/home/notes/note_topic_view.dart';
import 'package:flutter_douban/model/active_big_model.dart';
import 'package:flutter_douban/model/note_model.dart';
import 'package:flutter_douban/model/topic_model.dart';
import 'package:flutter_douban/tool_views/stance_page.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'home_card_view.dart';

Dio dio = new Dio();

class HomeNoteGridPage extends StatefulWidget {
  @override
  HomeNoteGridPageState createState() => new HomeNoteGridPageState();
}

class HomeNoteGridPageState extends State<HomeNoteGridPage>
    with AutomaticKeepAliveClientMixin {
  /// 下拉刷新控制器
  EasyRefreshController? _easyRefreshController;

  /// 独立的滚动视图 防止tab切换时触发下拉刷新
  ScrollController? _scrollController;

  /// 列表数组模型
  List<ActiveBigModel> _activeBigList = ActiveBigModelList([]).list;

  /// 头部数据
  List<TopicModel> _topicFirstList = TopicModelList([]).list;
  List<TopicModel> _topicTwoList = TopicModelList([]).list;

  /// 缓存的数据
  List<NoteModel> _noteList = [];

  /// id
  List<String> _idList = [];
  StreamSubscription<LoginEvent>? _loginSubscription;

  int page = 0;
  int limit = 10;
  bool hasMore = true;
  bool loading = true;
  bool error = false;
  String? errorMsg;

  @override
  void initState() {
    super.initState();
    _easyRefreshController = EasyRefreshController();
    _scrollController = ScrollController();
    _loginSubscription = EventBusUtil.listen((event) {
      setState(() {
        _onRefresh();
      });
    });
  }

  @override
  void dispose() {
    _easyRefreshController!.dispose();
    _scrollController!.dispose();
    super.dispose();
  }

  Future<void> _getData({bool replace = true}) async {
    _idList = [];

    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? numberId = prefs.getString(AppConfig.numberId);
    if(numberId == null){
      numberId = '123';
    }
    NoteDbProvider provider = new NoteDbProvider();
    List<NoteModel> list = [];
    provider.getAllNoteInfo(numberId).then((value) => {
          list = value,
          setState(() {
            _noteList = list;
            for (int i = 0; i < _noteList.length; i++) {
              _idList.add(_noteList[i].id!);
            }
            _getActiveData(replace: replace);
          }),
        });
  }

  /// 获取数据
  Future _getActiveData({bool replace = true}) async {
    try {
      /// 全部数据
      Map<String, dynamic> result =
          await HttpService.getHomeNoteData(page: page, pageSize: 10);

      /// 列表
      ActiveBigModelList activeBigModelList =
          ActiveBigModelList.fromJson(result['list']);

      TopicModelList topicFirstModelList =
          TopicModelList.fromJson(result['topics'][0]);
      TopicModelList topicTwoModelList =
          TopicModelList.fromJson(result['topics'][1]);

      setState(() {
        page++;
        if (replace) {
          if (page == 1) {
            _topicFirstList = topicFirstModelList.list;
            _topicTwoList = topicTwoModelList.list;
          }
          _activeBigList = activeBigModelList.list;
          for (int i = 0; i < _activeBigList.length; i++) {
            ActiveBigModel bigModel = _activeBigList[i];
            if (i > 1) {
              if (_idList.contains(bigModel.note!.id!)) {
                bigModel.note!.is_collection = true;
              } else {
                bigModel.note!.is_collection = false;
              }
            }
          }
        } else {
          _activeBigList.addAll(activeBigModelList.list);
        }
      });
    } catch (e) {
      setState(() {
        error = true;
        errorMsg = e.toString();
      });
    } finally {
      setState(() {
        loading = false;
      });
    }
  }

  // 刷新回调(null为不开启刷新)
  Future _onRefresh() async {
    if (error) {
      setState(() => error = false);
    }
    page = 0;
    await _getData();
    // 恢复刷新状态 使onLoad再次可用
    _easyRefreshController!.resetLoadState();
  }

  // 加载回调(null为不开启加载)
  Future _onLoad() async {
    if (hasMore) {
      await _getData(replace: false);
    }
    // 结束加载
    _easyRefreshController!.finishLoad(noMore: !hasMore);
  }

  @override
  Widget build(BuildContext context) {
    return EasyRefresh(
        // 开启首次加载刷新
        firstRefresh: true,
        // 加载时的loading
        firstRefreshWidget: StancePage(),
        // 空视图、异常视图
        // emptyWidget: PageFeedBack(
        //   loading: loading,
        //   error: error,
        //   empty: _songList.isEmpty,
        //   errorMsg: errorMsg,
        //   onErrorTap: () => _easyRefreshController.callRefresh(),
        //   onEmptyTap: () => _easyRefreshController.callRefresh(),
        // ).build(),
        header: CustomHeaderView(),
        footer: CustomFooterView(),
        controller: _easyRefreshController,
        enableControlFinishRefresh: false,
        enableControlFinishLoad: true,
        onRefresh: _onRefresh,
        onLoad: _onLoad,
        child: Column(
          children: [
            TopicView(
              topicFirstList: _topicFirstList,
              topicTwoList: _topicTwoList,
            ),
            Container(
              padding: EdgeInsets.only(
                left: 5,
                right: 5,
              ),
              color: Colors.grey[100],
              child: StaggeredGridView.countBuilder(
                controller: _scrollController,
                itemCount: _activeBigList.length,
                primary: false,
                shrinkWrap: true,
                crossAxisCount: 4,
                mainAxisSpacing: 10.0,
                crossAxisSpacing: 5.0,
                itemBuilder: (context, index) => ActiveCardView(
                  model: _activeBigList[index],
                ),
                staggeredTileBuilder: (index) => StaggeredTile.fit(2),
              ),
            ),
          ],
        ));
  }

  @override
  bool get wantKeepAlive => true;
}
